<!-- 当用户点击了修改箭头时，就会跳转到该页面进行用户信息的修改-->
<template>
  <van-form @submit="onSubmit">
    <!--    <van-cell-group inset>-->
    <!--      placeholder 是提示框文本  -->
    <van-field
        v-model="editUser.currentValue"
        :name="editUser.editKey"
        :label="editUser.editName"
        :placeholder="`请输入${editUser.editName}`"
    />
    <!--    </van-cell-group>-->
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
//查看当前路由信息
// 调用的是 User.vue 中的 route
//向后端发送 Post 请求
//第一个参数 url地址
//第二个参数是要传递的数据
// 将获取到的值赋给editUser对象中名为key的属性
// editKey可以为用户名 ( yulian174 )，密码 (152456) ，邮箱 ( qianxixi174@gmail.com )

import {useRoute, useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import myAxios from "../plugins/myAxios";
import {showFailToast, showSuccessToast, Toast} from "vant";
import {getCurrentUser} from "../services/user.ts";
import user from "./User.vue";

const route = useRoute();
const router = useRouter();

const editUser = ref({
  editKey: route.query.editKey,
  currentValue: route.query.currentValue,
  editName: route.query.editName,
})

onMounted(async () => {
  // 页面首次加载时获取当前用户信息
  const res = await myAxios.get('/user/current');

  user.value = await getCurrentUser();
  if (res.data) {
    user.value = res.data;
    showSuccessToast('获取用户信息成功！');
  } else {
    showFailToast('获取用户信息失败');
  }
})


const onSubmit = async () => {
  const currentUser = await getCurrentUser();

  if (!currentUser) {
    showFailToast('用户未登录');
    return;
  }

  console.log(currentUser, '当前用户')

  const res = await myAxios.post('/user/update', {
    'id': currentUser.id,
    [editUser.value.editKey as string]: editUser.value.currentValue,
  })
  console.log(res, '更新请求');
  // res.code === 0 &&
  if (res.code === 0 && res.data > 0) {
    showSuccessToast('修改成功');
    router.back();
  } else {
    showSuccessToast('修改错误');
  }
};
</script>

<style scoped>
</style>